# -*- coding: utf-8 -*-

import json
from channels.generic.websocket import AsyncWebsocketConsumer


class SystemNotificationConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user_id = self.scope['url_route']['kwargs']['user_id']
        self.group_name = 'notice_%s_%s' % (self.user_id)

        await self.channel_layer.group_add(self.group_name, self.channel_name)
        # 连接到WebSocket
        await self.accept()

    async def disconnect(self, close_code):
        # 断开WebSocket连接
        await self.channel_layer.group_discard(self.group_name, self.channel_name)

    async def receive(self, text_data=None, bytes_data=None):
        # 接收WebSocket消息
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        # 信息群发
        await self.channel_layer.group_send(
            self.group_name,
            {
                'type': 'system_message',
                'message': message
            })

    async def system_message(self, event):
        # 处理发送的消息
        message = event["message"]
        await self.send(
            text_data=json.dumps({'message': message})
        )
